#!/bin/sh -eu

. "$(dirname "$0")/common.sh"

test_cleanup() {
    umount "$scratch_dir/lower" || true
    umount "$scratch_dir/overlay" || true
}

chmod 755 "$scratch_dir"
mkdir -m755 "$scratch_dir/lower" "$scratch_dir/upper" "$scratch_dir/work" \
      "$scratch_dir/overlay"
mount -t tmpfs -o nosuid tmpfs "$scratch_dir/lower"
gcc -o "$scratch_dir/lower/suidexec" -Wall -Wextra "$(dirname "$0")/geteuid.c"
chmod 4755 "$scratch_dir/lower/suidexec"
mount -t overlay \
      -o "lowerdir=$scratch_dir/lower,upperdir=$scratch_dir/upper,workdir=$scratch_dir/work" \
      overlay "$scratch_dir/overlay"
if su -s /bin/sh nobody -c "chown nobody '$scratch_dir/overlay/suidexec'"; then
    echo >&2 "E: chown succeeded but should fail"
    exit 1
else
    echo "I: chown failed as expected"
fi
if [ -e "$scratch_dir/upper/suidexec" ]; then
    echo >&2 "E: suidexec was copied up"
    if [ "$(su -s /bin/sh nobody -c "$scratch_dir/upper/suidexec")" = 0 ]; then
	echo >&2 "E: copied-up suidexec is really setuid-root"
    fi
    exit 1
fi
